<?php

namespace App\Service;

use Aws\S3\S3Client;

class R2Service
{
    private $_client;
    private $_config;
    public function __construct()
    {
        $this->_config = config('app.r2');
        $this->_client = new S3Client([
            'version' => 'latest',
            'region' => $this->_config['region'],
            'endpoint' => $this->_config['endpoint'],
            'credentials' => [
                'key' => $this->_config['key'],
                'secret' => $this->_config['secret'],
            ],
            'use_path_style_endpoint' => true,
        ]);
    }
    
    function getMimeType($file_path){
        $extension = pathinfo($file_path, PATHINFO_EXTENSION);
        $contentTypeMap = [
                'jpg'  => 'image/jpeg',
                'jpeg' => 'image/jpeg',
                'png'  => 'image/png',
                'gif'  => 'image/gif',
                'mp4'  => 'video/mp4',
                'webm' => 'video/webm',
                'mov'  => 'video/quicktime',
                'avi'  => 'video/x-msvideo',
                'mp3'  => 'audio/mpeg',
        ];
        return $contentTypeMap[$extension] ?? 'application/octet-stream';
    }
    /**
     * 上传文件到R2
     * @param string $file_path 文件路径
     * @return array 上传结果
     */
    public function uploadFile($file_path,$key=null)
    {
        if (empty($file_path) || !is_file($file_path)){
            return false;
        }
        if (empty($key)){
            $key = str_replace('res/','',$file_path);
        }
        $result = $this->_client->putObject([
            'Bucket' => $this->_config['bucket'],
            'Key' => $key,
            'SourceFile' => $file_path,
            'ContentType' => $this->getMimeType($file_path),
        ]);
        if($result['@metadata']['statusCode'] == 200){
            $url = $this->_config['url'].'/'.$key;
            unlink($file_path);
            return $url;
        }
        return false;
    }
}
